package com.quanxiaoha.weblog.common.utils;

import com.quanxiaoha.weblog.common.exception.BaseExceptionInterface;
import com.quanxiaoha.weblog.common.exception.BizException;
import lombok.Data;

import java.io.Serializable;

@Data
public class R<T> implements Serializable {

    /**
     * 默认成功
     */
    private boolean success = true;

    /**
     * 相应码
     */
    private String code;
    /**
     * 相应消息
     */
    private String msg;
    /**
     * 相应数据
     */
    private T data;

    /**
     * 默认成功
     * @param data
     * @return
     * @param <T>
     */
    public static <T> R<T> ok(T data) {
        R<T> r = new R<T>();
        r.setCode("0");
        r.setData(data);
        return r;
    }

    public static <T> R<T> ok() {
        R<T> r = new R<T>();
        r.setCode("0");
        r.setData(null);
        return r;
    }

    /**
     * 默认失败
     * @param msg
     * @return
     * @param <T>
     */
    public static <T> R<T> fail(String msg) {
        R<T> r = new R<T>();
        r.setSuccess(Boolean.FALSE);
        r.setCode("1");
        r.setMsg(msg);
        return r;
    }

    /**
     * 自定义失败
     * @param code
     * @param msg
     * @return
     * @param <T>
     */
    public static <T> R<T> fail(String code, String msg) {
        R<T> r = new R<T>();
        r.setSuccess(Boolean.FALSE);
        r.setCode(code);
        r.setMsg(msg);
        return r;
    }

    /**
     * 系统错误失败
     */
    public static <T> R<T> fail(BizException bizException) {
        R<T> r = new R<T>();
        r.setSuccess(Boolean.FALSE);
        r.setCode("1");
        r.setMsg(bizException.getMessage());
        return r;
    }

    public static <T> R<T> fail(BaseExceptionInterface baseExceptionInterface) {
        R<T> response = new R<>();
        response.setSuccess(false);
        response.setCode(baseExceptionInterface.getErrorCode());
        response.setMsg(baseExceptionInterface.getErrorMsg());
        return response;
    }

}
